package com.vigor.bear.web.utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.vigor.bear.mybatis.Pagination;
import com.vigor.bear.web.bean.QueryModel;

public class DatatableUtils {

	/**
	 * 构造查询Model
	 * 
	 * @param aoData
	 * @return QueryModel
	 */
	public static QueryModel getQueryModel(String aoData) {
		JSONArray jsonarray = JSONArray.parseArray(aoData);

		String sEcho = null;
		int iDisplayStart = 0; // 起始索引
		int iDisplayLength = 0; // 每页显示的行数
		String sSearch = null; // 搜索字符

		for (int i = 0; i < jsonarray.size(); i++) {
			JSONObject obj = (JSONObject) jsonarray.get(i);
			if (obj.get("name").equals("sEcho"))
				sEcho = obj.get("value").toString();

			if (obj.get("name").equals("iDisplayStart"))
				iDisplayStart = obj.getIntValue("value");

			if (obj.get("name").equals("iDisplayLength"))
				iDisplayLength = obj.getIntValue("value");

			if (obj.get("name").equals("sSearch"))
				sSearch = obj.get("value").toString();
		}

		Pagination pagination = new Pagination(iDisplayStart, iDisplayLength);

		return new QueryModel(pagination, sEcho, sSearch);
	}

	/**
	 * 返回数据给Datatable显示
	 * 
	 * @param queryModel
	 * @param list
	 * @return Map<String, Object>
	 */
	public static Map<String, Object> getQueryResult(QueryModel queryModel,
			List<?> list) {
		Map<String, Object> map = new HashMap<String, Object>();

		if (list != null && list.size() > 0) {
			map.put("sEcho", queryModel.getsEcho());
			map.put("aaData", list);
			map.put("iTotalRecords", queryModel.getPagination().getTotal());
			map.put("iTotalDisplayRecords", queryModel.getPagination()
					.getTotal());
		} else {
			map.put("sEcho", queryModel.getsEcho());
			map.put("aaData", null);
			map.put("iTotalRecords", 0);
			map.put("iTotalDisplayRecords", 0);
		}

		return map;
	}

	public static Map<String, Object> getQueryResult(String sEcho, List<?> list) {
		Map<String, Object> map = new HashMap<String, Object>();

		if (list != null && list.size() > 0) {
			map.put("sEcho", sEcho);
			map.put("aaData", list);
			map.put("iTotalRecords", list.size());
			map.put("iTotalDisplayRecords", list.size());
		} else {
			map.put("sEcho", sEcho);
			map.put("aaData", null);
			map.put("iTotalRecords", 0);
			map.put("iTotalDisplayRecords", 0);
		}

		return map;
	}

}
